package com.lntea.netty.im.handler;

import com.lntea.netty.im.packet.LoginRequestPacket;
import com.lntea.netty.im.packet.LoginResponsePacket;
import com.lntea.netty.im.packet.common.Session;
import com.lntea.netty.im.packet.common.SessionUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.Random;

/**
 * 登录请求消息Handler
 */
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket msg) throws Exception {
        ctx.channel().writeAndFlush(login(ctx, msg));
    }

    /**
     * 登录处理逻辑
     * @param reqPacket
     * @return
     */
    private LoginResponsePacket login(ChannelHandlerContext ctx, LoginRequestPacket reqPacket) {
        String userName = reqPacket.getUserName();
        System.out.println(new Date() + String.format(": 用户%s开始登陆", userName));
        LoginResponsePacket respPacket = new LoginResponsePacket();
        respPacket.setUserName(userName);
        // 校验通过
        if (valid(reqPacket)) {
            // 分配随机用户id
            String userId = randomUserId();
            // 组装响应数据包
            respPacket.setUserId(userId);
            respPacket.setSuccess(true);
            // 绑定会话
            SessionUtil.bindSession(new Session(userId, userName), ctx.channel());

            System.out.println(new Date() + String.format(": 用户%s登陆成功", userName));
        } else {
            respPacket.setSuccess(false);
            respPacket.setReason("登录校验失败");
            System.out.println(new Date() + String.format(": 用户%s登陆失败，原因：%s",
                    userName, respPacket.getReason()));
        }
        return respPacket;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionUtil.unbindSession(ctx.channel());
    }

    /**
     * 随机生成用户id
     * @return
     */
    private String randomUserId() {
        return "u" + new Random().nextInt(100);
    }

    /**
     * 校验客户端登录
     * @param packet
     * @return
     */
    private boolean valid(LoginRequestPacket packet) {
        if (packet.getPassword().equals("pwd")) {
            return true;
        }
        return false;
    }
}
